<!DOCTYPE html>
<html>
<head>
  <script src="http://yandex.st/jquery/1.7.1/jquery.min.js"></script>
  <script src="http://yandex.st/jquery/flot/0.7/jquery.flot.min.js"></script>
  <script src="http://cdn.jsdelivr.net/sockjs/0.3/sockjs.min.js"></script>
  <script>
    $(function() {
        var graph_items = ['sessions_active',
                           'connections_active',
                           'connections_ps',
                           'packets_sent_ps',
                           'packets_recv_ps'
                           ];

        // Flot stuff
        var data = [], totalPoints = 60;

        for (var i = 0; i < totalPoints; ++i)
        {
          item = {};

          for (var j = 0; j < graph_items.length; ++j)
            item[graph_items[j]] = 0;

          data.push(item);
        }

        function appendData(values)
        {
            if (data.length >= totalPoints)
              data = data.slice(1);

            data.push(values);
        }

        function convertValues(name)
        {
          var res = [];
          for (var i = 0; i < data.length; ++i)
          {
            res.push([i, data[i][name]]);
          }
          return res;
        }

        function prepareGraphData()
        {
          var res = [];

          for (var i in graph_items)
          {
            var name = graph_items[i];

            res.push({
              label: name,
              data: convertValues(name)
            });
          }

          return res;
        }

        function plotStats(data)
        {
            appendData(data);

            plot.setData(prepareGraphData());
            plot.setupGrid();
            plot.draw();

            // Update table
            var placeholder = $('#table');
            placeholder.empty();

            var table = $('<table/>');
            for (var i in data)
            {
              var item = data[i];

              $('<tr/>')
                .append($('<td/>').text(i))
                .append($('<td/>').text(item))
                .appendTo(placeholder);
            }

            table.appendTo(placeholder);
        }

        var options = {
          series: {
              lines: {
                  show: true
              }
          },
          yaxis: {
            min: 0,
          },
          xaxis: {
            show: false
          }
        };

        //var plot = $.plot($('#placeholder'), [], options);
        var plot = $.plot('#placeholder', prepareGraphData(), options);

        var conn = new SockJS('http://' + window.location.host + '/statsconn');
        conn.onmessage = function(e) {
           plotStats(JSON.parse(e.data));
        }
    });
</script>
</head>
<body>
  <h3>Connection stats!</h3>
  <div>
   <div id="placeholder" style="width:920px;height:400px;float:left;"></div>
   <div id="table"></div>
  </div>
</body>
</html>
